//
//  EPhotoWall.m
//  Common
//
//  Created by guoshiqing on 2018/6/1.
//  Copyright © 2018年 www.bitkinetic.com. All rights reserved.
//

#import "EPhotoWall.h"
#import "UIView+DDAddition.h"

#define kImagePositionx @"positionx"
#define kImagePositiony @"positiony"
#define kBetweenWidth 10

@interface EPhotoWall ()<EPhotoDelegate>
// 保存照片的位置
@property (strong, nonatomic) NSMutableArray *arrayPositions;
// 保存照片对象
@property (strong, nonatomic) NSMutableArray *arrayPhotos;
// 保存照片的资源
@property (strong, nonatomic) NSMutableArray *arrayPhotoData;
// 几行几列
@property (nonatomic, assign) NSUInteger gRow;
// 最大个数
@property (nonatomic, assign) NSUInteger gMaxNum;
// 单个照片的“框&高”
@property (nonatomic, assign) CGFloat gSize;
@end

@implementation EPhotoWall

- (id)initWithFrame:(CGRect)frame withRow:(NSUInteger)row withMaxNumber:(NSUInteger)maxNum
{
    self = [super initWithFrame:CGRectMake(0., 0., frame.size.width, 0.)];
    if (self) {
        
        // 获得全局变量
        self.gRow = row;
        self.gMaxNum = maxNum;
        self.gSize = (frame.size.width - (row+1)*kBetweenWidth) / row;
        
        // 设置背景色
        self.backgroundColor = [UIColor whiteColor];
        
        CGFloat xPosition = 5;
        CGFloat yPosition = 5;
        NSString *xStr = @"";
        NSString *yStr = @"";
        int     iRows    = 0;
        int     iColumns = 0;
        
        self.arrayPositions = [[NSMutableArray alloc] init];
        
        // 定义3*3矩阵的坐标,多1个加号的位置
        int maxSize = (int)(self.gRow*self.gRow + 1);
        for (int i = 0; i < maxSize; ++i) {
            
            // 计算行数
            iRows    = i/self.gRow;
            iColumns = i%self.gRow;
            
            // 计算x坐标
            xPosition = (iColumns+1)*kBetweenWidth + iColumns*self.gSize;
            
            // 计算y坐标
            yPosition = (iRows+1) * kBetweenWidth + iRows*self.gSize;
            
            // 转换坐标类型
            xStr = [NSString stringWithFormat:@"%f", xPosition];
            yStr = [NSString stringWithFormat:@"%f", yPosition];
            
            NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:xStr, kImagePositionx, yStr, kImagePositiony, nil];
            
            [self.arrayPositions addObject:dic];
        }
        // 设置容量
        self.arrayPhotos = [NSMutableArray arrayWithCapacity:1];
        // 初始化图片数据
        self.arrayPhotoData = [[NSMutableArray alloc] init];
    }
    return self;
}

- (void)setPhotos:(NSArray*)photos resourceType:(RESOURCETYPE)type
{
    [self.arrayPhotos removeAllObjects];
    NSUInteger count = [photos count];
    for (int i=0; i<count; i++) {
        NSDictionary *dictionaryTemp = [self.arrayPositions objectAtIndex:i];
        CGFloat originx = [[dictionaryTemp objectForKey:kImagePositionx] floatValue];
        CGFloat originy = [[dictionaryTemp objectForKey:kImagePositiony] floatValue];
        EPhoto *photoTemp = [[EPhoto alloc] initWithOrigin:CGPointMake(originx, originy) withSize:self.gSize];
        photoTemp.delegate = self;
        photoTemp.tag = i; // 保存索引，为了放大查看
        [photoTemp setPhotoUrl:[photos objectAtIndex:i] resouceType:type];
        [self addSubview:photoTemp];
        [self.arrayPhotos addObject:photoTemp];
        [self.arrayPhotoData addObject:[photos objectAtIndex:i]];
    }
    
    NSDictionary *dictionaryTemp = [self.arrayPositions objectAtIndex:count];
    CGFloat originx = [[dictionaryTemp objectForKey:kImagePositionx] floatValue];
    CGFloat originy = [[dictionaryTemp objectForKey:kImagePositiony] floatValue];
    EPhoto *photoTemp = [[EPhoto alloc] initWithOrigin:CGPointMake(originx, originy)  withSize:self.gSize];
    photoTemp.delegate = self;
    
    photoTemp.hidden = NO;
    [photoTemp setPhotoType:PhotoTypeAdd];
    [self.arrayPhotos addObject:photoTemp];
    [self addSubview:photoTemp];
    
    CGFloat frameHeight = -1;
    
    // 计算照片墙的高度
    NSUInteger iRows = 1;
    if (0 < count) {
        iRows = (count+self.gRow-1)/self.gRow;
    }
    
    NSUInteger countPhoto = [self.arrayPhotos count];
    NSUInteger maxCounts = [self.arrayPositions count];
    
    // 判断如果加上加号按钮超过最大个数，则父view的高度不增加
    if (countPhoto > maxCounts)
    {
        return;
    }
    else
    {
        frameHeight = iRows*self.gSize + (iRows+1)*kBetweenWidth;
    }
    
    self.height = frameHeight;
    //    self.frame = CGRectMake(0., 0., DEVICE_SCREEN_WIDTH, frameHeight);
    
    [self reloadPhotos:YES];
}

// 添加单张照片
- (void)addPhoto:(id)string resourceType:(RESOURCETYPE)type
{
    // 获得下个图片的索引号, “加号”按钮往后面移动
    NSUInteger index = [self.arrayPhotos count] - 1;
    
    // 获得下个图片的位置
    NSDictionary *dictionaryTemp = [self.arrayPositions objectAtIndex:index];
    CGFloat originx = [[dictionaryTemp objectForKey:kImagePositionx] floatValue];
    CGFloat originy = [[dictionaryTemp objectForKey:kImagePositiony] floatValue];
    
    // 生成对象
    EPhoto *photoTemp = [[EPhoto alloc] initWithOrigin:CGPointMake(originx, originy)  withSize:self.gSize];
    photoTemp.delegate = self;
    [photoTemp setPhotoUrl:string resouceType:type];
    [self.arrayPhotoData addObject:string];
    
    // 添加到数组，添加到界面上
    [self.arrayPhotos insertObject:photoTemp atIndex:index];
    photoTemp.tag = index; // 保存索引，为了放大查看
    [self addSubview:photoTemp];
    [self reloadPhotos:YES];
}


// 添加多张图片
- (void)addPhotos:(NSArray *)photos  resourceType:(RESOURCETYPE)type
{
    for (id string in photos) {
        // 获得下个图片的索引号, “加号”按钮往后面移动
        NSUInteger index = [self.arrayPhotos count] - 1;
        
        // 获得下个图片的位置
        NSDictionary *dictionaryTemp = [self.arrayPositions objectAtIndex:index];
        CGFloat originx = [[dictionaryTemp objectForKey:kImagePositionx] floatValue];
        CGFloat originy = [[dictionaryTemp objectForKey:kImagePositiony] floatValue];
        
        // 生成对象
        EPhoto *photoTemp = [[EPhoto alloc] initWithOrigin:CGPointMake(originx, originy)  withSize:self.gSize];
        photoTemp.delegate = self;
        [photoTemp setPhotoUrl:string resouceType:type];
        [self.arrayPhotoData addObject:string];
        
        // 添加到数组，添加到界面上
        [self.arrayPhotos insertObject:photoTemp atIndex:index];
        photoTemp.tag = index; // 保存索引，为了放大查看
        [self addSubview:photoTemp];
    }
    
    [self reloadPhotos:YES];
}

- (void)deletePhotoByIndex:(NSUInteger)index
{
    // 删除时，重置加号按钮，为设置最大个数做的
    EPhoto *addPhoto = [self.arrayPhotos lastObject];
    addPhoto.hidden = NO;
    
    // 删除指定索引的对象，并刷新
    EPhoto *photoTemp = [self.arrayPhotos objectAtIndex:index];
    [self.arrayPhotos removeObject:photoTemp];
    
    // 重新设定tag值，不能因为删除操作导致断层
    NSUInteger tagTmp = 0;
    for (EPhoto *photo in self.arrayPhotos) {
        photo.tag = tagTmp;
        tagTmp ++;
    }
    
    [self.arrayPhotoData removeObjectAtIndex:index];
    [photoTemp removeFromSuperview];
    [self reloadPhotos:YES];
}

#pragma mark - 删除所有图片，除了加号按钮
- (void)deletePhotoExceptAddBtn
{
    NSUInteger counts = self.arrayPhotoData.count;
    for (NSUInteger i = 0; i <  counts; ++i) {
        [self deletePhotoByIndex:0];
    }
}


#pragma mark - 添加照片
- (void)photoAdd:(EPhoto*)photo
{
    NSUInteger type = [photo getPhotoType];
    if (type == PhotoTypeAdd) {
        if ([self.delegate respondsToSelector:@selector(photoWallAddAction)]) {
            [self.delegate photoWallAddAction];
        }
    }
}

#pragma mark - 删除照片
- (void)photoDel:(EPhoto*)photo
{
    NSUInteger type = [photo getPhotoType];
    if (type == PhotoTypePhoto) {
        NSUInteger index = [self.arrayPhotos indexOfObject:photo];
        if ([self.delegate respondsToSelector:@selector(photoWallDelAction:)]) {
            [self.delegate photoWallDelAction:index];
        }
    }
}

#pragma mark - 放大查看照片,分为网络图片(查看模式)和本地图片(编辑模式)
- (void)photoEnlarge:(EPhoto*)photo
{
    NSUInteger type = [photo getPhotoType];
    
    if ([self.delegate respondsToSelector:@selector(photoWallEnlargeAction:fromIndex:)]) {
        [self.delegate photoWallEnlargeAction:type fromIndex:photo.tag];
    }
}


- (void)photoMoveFinished:(EPhoto*)photo
{
    CGPoint pointPhoto = CGPointMake(photo.frame.origin.x, photo.frame.origin.y);
    CGFloat space = -1;
    NSUInteger oldIndex = [self.arrayPhotos indexOfObject:photo];
    NSUInteger newIndex = -1;
    
    NSUInteger count = [self.arrayPhotos count] - 1;
    for (int i=0; i<count; i++) {
        
        NSDictionary *dictionaryTemp = [self.arrayPositions objectAtIndex:i];
        CGFloat originx = [[dictionaryTemp objectForKey:kImagePositionx] floatValue];
        CGFloat originy = [[dictionaryTemp objectForKey:kImagePositiony] floatValue];
        CGPoint pointTemp = CGPointMake(originx, originy);
        CGFloat spaceTemp = [self spaceToPoint:pointPhoto FromPoint:pointTemp];
        if (space < 0) {
            space = spaceTemp;
            newIndex = i;
        } else {
            if (spaceTemp < space) {
                space = spaceTemp;
                newIndex = i;
            }
        }
    }
    
    [self.arrayPhotos removeObject:photo];
    [self.arrayPhotos insertObject:photo atIndex:newIndex];
    
    [self reloadPhotos:NO];
    
    if ([self.delegate respondsToSelector:@selector(photoWallMovePhotoFromIndex:toIndex:)]) {
        [self.delegate photoWallMovePhotoFromIndex:oldIndex toIndex:newIndex];
    }
}

- (void)reloadPhotos:(BOOL)add
{
    NSUInteger count = -1;
    if (add) {
        count = [self.arrayPhotos count];
    } else {
        count = [self.arrayPhotos count] - 1;
    }
    for (int i=0; i<count; i++) {
        NSDictionary *dictionaryTemp = [self.arrayPositions objectAtIndex:i];
        CGFloat originx = [[dictionaryTemp objectForKey:kImagePositionx] floatValue];
        CGFloat originy = [[dictionaryTemp objectForKey:kImagePositiony] floatValue];
        
        EPhoto *photoTemp = [self.arrayPhotos objectAtIndex:i];
        [photoTemp moveToPosition:CGPointMake(originx, originy)];
    }
    
    CGFloat frameHeight = -1;
    
    NSUInteger countPhoto = [self.arrayPhotos count];
    NSUInteger maxCounts = [self.arrayPositions count];
    
    // 计算当前的行
    NSUInteger iRows = (count+(self.gRow-1))/self.gRow;
    
    // 如果超过最大个数，则加号按钮隐藏
    if (0 == self.gMaxNum || count > self.gMaxNum) {
        EPhoto *addPhoto = [self.arrayPhotos lastObject];
        addPhoto.hidden = YES;
    }
    
    // 判断如果加上加号按钮超过最大个数，则父view的高度不增加
    if (countPhoto >= maxCounts)
    {
        return;
    }
    else
    {
        frameHeight = iRows*self.gSize + (iRows+1)*kBetweenWidth;
    }
    
    self.height = frameHeight;
    //    self.frame = CGRectMake(0., 0., DEVICE_SCREEN_WIDTH, frameHeight);
}

- (CGFloat)spaceToPoint:(CGPoint)point FromPoint:(CGPoint)otherPoint
{
    float x = point.x - otherPoint.x;
    float y = point.y - otherPoint.y;
    return sqrt(x * x + y * y);
}


#pragma mark - 把照片数据暴露给外面访问
- (NSMutableArray *)getPhotos
{
    return self.arrayPhotoData;
}

- (id)getPhotoFileByIndex:(NSInteger)index
{
    return [self.arrayPhotos objectAtIndex:index];
}

#pragma mark - 设置隐藏加号按钮
- (void)setEditModel:(BOOL)canEdit
{
    if (canEdit) {
        EPhoto *viewTemp = [self.arrayPhotos lastObject];
        viewTemp.hidden = NO;
    } else {
        EPhoto *viewTemp = [self.arrayPhotos lastObject];
        viewTemp.hidden = YES;
    }
    
    NSUInteger count = [self.arrayPhotos count]-1;
    for (int i=0; i<count; i++) {
        EPhoto *viewTemp = [self.arrayPhotos objectAtIndex:i];
        [viewTemp setEditModel:canEdit];
    }
    [self reloadPhotos:NO];
}

#pragma mark - 返回照片墙的高度
- (CGFloat)heightOfPhotoWall
{
    return self.frame.size.height;
}


@end
